-module(sew).
-compile(export_all).
-include("/usr/local/lib/yaws/include/yaws.hrl").
-include("sew.hrl").
-include("sew_app.hrl").

%%
%% TODO: Trap_exit the formatter_supervisor and restart it on errors
%%


start() ->
    application:start(inets),
	start_yaws(),
    compile(),
	spawn({?MODULE,start_formatter}).

compile() ->
    compile([]).

compile_dev() ->
    compile([{auto_compile, true}]).

compile_update() ->
    compile([{last_compile_time, auto}]).

compile(Opts) ->
    erlyweb:compile(?APP_PATH,
		    [{erlydb_driver, mysql}, {erlydb_timeout, 20000} | Opts]).

start_yaws() ->
	application:load(yaws),
	application:set_env(yaws, embedded, true),
	application:set_env(yaws, id, "sew"),
	application:start(yaws),
	GC = #gconf{
	        trace = false
	    },
	SC = #sconf{
	        port = ?YAWS_PORT,
	        servername = "sew",
	        listen = {0, 0, 0, 0},
	        docroot = ?APP_PATH ++ "/www",
	        appmods = [{"/", erlyweb}],
			opaque = [{"appname", "sew"}]
	    },
	yaws_api:setconf(GC, [[SC]]).
	
start_formatter() ->
	process_flag(trap_exit, true),	 
	formatter_supervisor:start_link(),
	formatter_loop().
	
formatter_loop() ->
	receive
		{'EXIT', _, _} ->
			formatter_supervisor:start_link(),
			formatter_loop();
		_ ->
			formatter_loop()
	end.
	
	
create_db() -> 
	couchdb:create_database(?DB_DATABASE),
	
	couchdb:create_view(
		"get",
		[
			{<<"page">>, <<"function(doc){if(doc.type=='page') emit(doc.uri, {title: doc.title, rendered: doc.rendered}); }">>},
			{<<"page-full">>, <<"function(doc){if(doc.type=='page') emit(doc.uri, doc); }">>}
		]
	),	
	WelcomeData = <<"
Welcome to **sew, a simple erlang wiki**

This is an early 0.1-alpha-whatchamacallit proof-of-concept wiki written in [Erlang][1] on top of [Yaws][2], [ErlyWeb][3] and [CouchDB][4]

At this early stage it can only create/edit/delete articles so as to prove that this all is doable in Erlang :-)

Text formatting is provided by [Markdown][5], which is grand for simple text formatting (and this wiki doesn't require much).

You are free to play around, see a [longish example][6] and look at the code


  [1]: http://erlang.org/
  [2]: http://yaws.hyber.org/
  [3]: http://erlyweb.org/
  [4]: http://incubator.apache.org/couchdb/
  [5]: http://daringfireball.net/projects/markdown/
  [6]: /wiki/sample
	">>,
	SampleData = <<"
##This is a rundown of most Markdown elements
*For more information about Markdown syntax visit Markdown site at [http://daringfireball.net/projects/markdown/][0]*

###Paragraphs
A paragraph is one or more consecutive lines of text separated by one or more blank lines. Normal paragraphs should not be indented with spaces or tabs. This text is an example of a paragraph.


Separate paragraphs by two line breaks. To introduce a single line break,  
leave two empty spaces at the end of the line

###Text formatting

Text formatting: *emphasis* (i.e., italics), **strong emphasis** (i.e., boldface), ***bold italics***

###Code

Code can be either inline or block-level. This is an `example of inline code`. Followed by

    several lines
    of multiline
    block of code

###Lists

Lists can either be unordered:

  - List item
  - Another item
    - Nested item  
      - Yet another nested list item

or ordered:

  1. An item in an enumerated (ordered) list
  2. Another item in an enumerated list

###Headings

HTML headings are produced by placing a number of hashes before the header text corresponding to the level of heading desired (HTML offers six levels of headings), like so:

# First-level heading

#### Fourth-level heading

The first two heading levels also have an alternate syntax:

First-level heading
===================

Second-level heading
--------------------

###Blockquotes

> This text will be enclosed in an HTML blockquote element.

>> second level blockquote

###Links

[This is an inline link](link.address.here \"link title here\")

[This link uses a list of links at the end of the document][2]

###Images

Inline image: ![Alt text here](http://erlang.org/images/erlang.gif \"Image title here\")

Image from the link list: ![Alt text here][3]

###Horizontal rules
Horizontal rules are created by placing three or more hyphens, asterisks, or underscores on a line by themselves. You may use spaces between the hyphens or asterisks. Each of the following lines will produce a horizontal rule:

* * *
***
*****
- - -
---------------------------------------

###Escaping HTML

Markdown automatically escapes ampersands, &, and left angle brackets, <,  and leaves HTML entities intact: &copy;

###Using HTML
You can use any HTML you want. However, Markdown parser will not work inside block-level tags (&lt;p>, &lt;table>, &lt;div> etc.)

  [0]: http://daringfireball.net/projects/markdown/
  [1]: http://en.wikipedia.org/wiki/Markdown#Syntax_examples
  [2]: http://bogus_link/
  [3]: http://erlang.org/images/erlang.gif


	">>,
	WelcomeDataRendered = format:markdown(WelcomeData),
	SampleDataRendered = format:markdown(SampleData),
	couchdb:create_document({"main", [
			{<<"uri">>, <<"main">>},
			{<<"title">>, <<"Welcome">>},
			{<<"data">>, WelcomeData},
			{<<"rendered">>, WelcomeDataRendered},
			{<<"type">>, <<"page">>}
	]}),
	couchdb:create_document({sample, [
			{<<"uri">>, <<"sample">>},
			{<<"title">>, <<"Sample">>},
			{<<"data">>, SampleData},
			{<<"rendered">>, SampleDataRendered},
			{<<"type">>, <<"page">>}
	]}).
	